#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import sys
import json
import bbki
import bbki.util
import mrget
import strict_hwcfg

sys.path.append('/usr/lib64/fpemud-os-sysman')
from fm_util import Util
from fm_util import InfoPrinter
from fm_util import PrintLoadAvgThread
from helper_bbki import BbkiWrapper


p = InfoPrinter(indent=int(sys.argv[1]))                        # FIXME: print should be done by infoPrinter
bootEntrySpec = bbki.BootEntrySpec(json.loads(sys.argv[2]))
bKernelBuildNeeded = Util.str01ToBool(sys.argv[3])
oldBootEntryPostfix = sys.argv[4]
oldBootEntryKernelConfigFile = sys.argv[5]
resultFile = sys.argv[6]

mrget.init(system_or_user=True)

machine = strict_hwcfg.probe()
bbkiObj = BbkiWrapper(machine, bStrict=False)
with bbkiObj.getKernelInstaller(bootEntrySpec) as bbkiKernelBuilder:
    print("        - Fetching...")
    bbkiKernelBuilder.fetch_kernel()
    for name in bbkiKernelBuilder.spec.kernel_addons:
        bbkiKernelBuilder.fetch_kernel_addon(name)

    print("        - Extracting...")
    bbkiKernelBuilder.unpack()

    print("        - Patching...")
    bbkiKernelBuilder.patch_kernel()

    print("        - Generating .config file...")
    bbkiKernelBuilder.generate_kernel_config_file()

    if bKernelBuildNeeded or not bbki.util.compare_kernel_config_files(oldBootEntryKernelConfigFile, bbkiKernelBuilder.get_kernel_config_filepath()):
        with PrintLoadAvgThread("        - Building and installing..."):
            bbkiKernelBuilder.install_kernel()
        bKernelBuildNeeded = True
        bootEntryPostfix = bbkiKernelBuilder.get_target_boot_entry().postfix
    else:
        print("        - Same kernel, no need for building and installing...")
        bootEntryPostfix = oldBootEntryPostfix

os.makedirs(os.path.dirname(resultFile), exist_ok=True)
with open(resultFile, "w", encoding="iso8859-1") as f:
    f.write("%s\n" % (Util.boolToStr01(bKernelBuildNeeded)))
    f.write("%s\n" % (bootEntryPostfix))
